import { login, logout, getAvatar /* , checkToken */ } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import router, { resetRouter } from '@/router'

const state = {
  token: getToken(),
  username: '',
  avatar: '',
  is_superuser: false
}

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_USERNAME: (state, username) => {
    state.username = username
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_SUPERUSER: (state, is_superuser) => {
    state.is_superuser = is_superuser
  }
}

const actions = {
  // 用户登录
  login({ commit }, userInfo) {
    const { username, password } = userInfo
    return new Promise((resolve, reject) => {
      login({ username: username.trim(), password: password })
        .then(response => {
          if (response.code === 200) {
            const { data } = response
            if (!data.token) {
              reject(new Error('Token不存在'))
              return
            }
            
            // 保存 token
            setToken(data.token)
            commit('SET_TOKEN', data.token)
            
            // 保存 refresh token
            localStorage.setItem('refresh_token', data.refresh)
            
            // 保存用户信息
            if (data.user) {
              commit('SET_USERNAME', data.user.username)
              commit('SET_SUPERUSER', data.user.is_superuser)
              
              // 保存用户信息到 localStorage
              localStorage.setItem('user_info', JSON.stringify(data.user))
            }
            
            resolve()
          } else {
            reject(new Error(response.message || '登录失败'))
          }
        })
        .catch(error => {
          reject(error)
        })
    })
  },

  // 获取用户头像信息
  getAvatar({ commit, state }) {
    return new Promise((resolve, reject) => {
      // 首先尝试从 localStorage 获取头像
      const userInfo = localStorage.getItem('user_info')
      if (userInfo) {
        const parsedUserInfo = JSON.parse(userInfo)
        if (parsedUserInfo.avatar) {
          commit('SET_USERNAME', parsedUserInfo.username)
          commit('SET_AVATAR', parsedUserInfo.avatar)
          resolve(parsedUserInfo)
          return
        }
      }

      // 如果没有本地头像信息，则从服务器获取
      getAvatar().then(response => {
        if (response.code === 200) {
          const { data } = response
          if (!data) {
            reject('获取用户头像失败')
            return
          }

          // 保存用户信息到store
          commit('SET_USERNAME', data.username)
          commit('SET_AVATAR', data.avatar)
          
          // 构建用户信息对象并保存到 localStorage
          const userInfo = {
            id: data.id,
            username: data.username,
            avatar: data.avatar
          }
          localStorage.setItem('user_info', JSON.stringify(userInfo))
          
          resolve(data)
        } else {
          reject(new Error(response.message || '获取用户头像失败'))
        }
      }).catch(error => {
        reject(error)
      })
    })
  },

  // 用户登出
  logout({ commit, state, dispatch }) {
    return new Promise((resolve, reject) => {
      logout(state.token).then(() => {
        // 清除所有状态
        commit('SET_TOKEN', '')
        commit('SET_USERNAME', '')
        commit('SET_AVATAR', '')
        commit('SET_SUPERUSER', false)
        
        // 清除本地存储
        removeToken()
        localStorage.removeItem('user_info')
        localStorage.removeItem('refresh_token')
        
        // 清除Remember me保存的信息
        localStorage.removeItem('fs_remembered_username')
        localStorage.removeItem('fs_remembered_password')
        localStorage.removeItem('fs_remember_state')
        
        // 重置路由
        resetRouter()
        
        // 清除标签页
        dispatch('tagsView/delAllViews', null, { root: true })
        
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // 重置 Token
  resetToken({ commit }) {
    return new Promise(resolve => {
      commit('SET_TOKEN', '')
      commit('SET_USERNAME', '')
      commit('SET_AVATAR', '')
      commit('SET_SUPERUSER', false)
      removeToken()
      localStorage.removeItem('user_info')
      localStorage.removeItem('refresh_token')
      resolve()
    })
  },

  // dynamically modify permissions
  async changeRoles({ commit, dispatch }, role) {
    const token = role + '-token'

    commit('SET_TOKEN', token)
    setToken(token)

    await dispatch('getAvatar')

    resetRouter()

    // generate accessible routes map based on roles
    const accessRoutes = await dispatch('permission/generateRoutes', null, { root: true })
    // dynamically add accessible routes
    router.addRoutes(accessRoutes)

    // reset visited views and cached views
    dispatch('tagsView/delAllViews', null, { root: true })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
